/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.Branch;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Young Ran
 */
public class BranchDAO {
    
    private Connection cn;
    private PreparedStatement pstm;
    private CallableStatement cs;
    
    public BranchDAO() {
        cn = DB_Util.getConnection();
    }
    
    private ArrayList<Branch> getBranchData(ResultSet rs) throws SQLException {
        ArrayList<Branch> list = new ArrayList<Branch>();
        while (rs.next()) {
            Branch e = new Branch();
            e.setId(rs.getInt("BranchId"));
            e.setName(rs.getString("BranchName"));
            e.setAddress(rs.getString("BranchAddress"));
            e.setPhone(rs.getString("BranchPhone"));
            e.setEmail(rs.getString("BranchEmail"));           
            list.add(e);
        }
        return list;
    }
    
    //DISPLAY BRANCHES:
    public ArrayList<Branch> getAllBranch() throws SQLException {
        cs = cn.prepareCall("{call SP_Display_Branch}");
        ResultSet rs = cs.executeQuery();
        return getBranchData(rs);
    }
    public void addBranch(Branch item) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Add_Branch(?,?,?,?)}");
        cs.setNString(1, item.getName());
        cs.setNString(2, item.getAddress());
        cs.setNString(3, item.getPhone());
        cs.setNString(4, item.getEmail());
        cs.execute();
    }
    public void editBranch(Branch item) throws SQLException{
        cs = cn.prepareCall("{call SP_Edit_Branch(?,?,?,?,?)}");
         cs.setInt(1, item.getId());
        cs.setNString(2, item.getName());
        cs.setNString(3, item.getAddress());
        cs.setNString(4, item.getPhone());
        cs.setNString(5, item.getEmail());
        cs.execute();
    }
      public void deleteBranch(int id) throws SQLException{
        cs = cn.prepareCall("{call SP_Delete_Branch(?)}");
        cs.setInt(1, id);
        cs.execute();
    }
}
